<template>
    <!-- Dialog 对话框实现地址编辑弹窗显示， 饿了么ui组件 -->
    <!-- model-value是否显示 Dialog -->
    <!-- title说明：Dialog 对话框 Dialog 的标题， 也可通过具名 slot （见下表）传入 -->
    <!-- dialogVisible是从父组件传过来 -->
    <el-dialog :model-value="dialogVisible" :title="dialogTitle" width="50%">
        <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="100px"
        >
            <el-form-item label="收货人姓名" prop="userName">
                <el-input v-model="ruleForm.userName" style="width: 400px" />
            </el-form-item>
            <el-form-item label="联系电话" prop="telNumber">
                <el-input v-model="ruleForm.telNumber" style="width: 400px" />
            </el-form-item>
            <el-form-item label="省市县" prop="address">
                <el-input v-model="ruleForm.address" style="width: 400px" />
            </el-form-item>
            <el-form-item label="详细地址" prop="detailInfo">
                <el-input v-model="ruleForm.detailInfo" type="textarea" :rows="4" style="width: 400px"/>
            </el-form-item>
            <el-form-item label="是否默认地址" prop="isDefault">
                <el-switch v-model="ruleForm.isDefault"></el-switch>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleConfirm">确认</el-button>
                <el-button type="primary" @click="handleClose">取消</el-button>
            </div>
        </template>
    </el-dialog>
  </template>
  
  <script setup>
  import { defineEmits, defineProps, ref, watch } from "vue";
  import axios from "@/util/axios";
  import { ElMessage } from "element-plus";
  
  // 定义组件接收的属性
  const props = defineProps({
    // 对话框详情的标题，类型为字符串，默认值为 null，也是必须要传递的属性
    dialogTitle: {
        type: String,
        default: null,
        required: true,
    },
    // 用于控制对话框是否可见的布尔值，默认值为 false，同样是必须传递的属性
    dialogVisible: {
        type: Boolean,
        default: false,
        required: true,
    },
    // 新增属性，用于接收选中的地址数据
    selectedAddress: {
        type: Object,
        default: null,
    },
  });
  
  // 创建一个响应式对象ruleForm，用于存储地址相关的表单数据，初始值设置了各个字段的默认情况
  const ruleForm = ref({
    id: -1,
    userName: "",
    telNumber: "",
    address: "",
    detailInfo: "",
    isDefault: false,
  });
  
  // 定义表单验证规则，是一个响应式对象
  const rules = ref({
    userName: [
        {
            required: true,
            message: "请输入收货人姓名！",
        },
    ],
    telNumber: [
        {
            required: true,
            message: "请输入联系电话！",
        },
    ],
    address: [
        {
            required: true,
            message: "请输入省市县！",
        },
    ],
    detailInfo: [
        {
            required: true,
            message: "请输入详细地址！",
        },
    ],
  });
  
  const ruleFormRef = ref(null);
  
  // 定义父组件事件，这里定义了可以向父组件触发的事件名称
  const emits = defineEmits([
    "update:modelValue",
    "initAddressList",
  ]);
  
  // 关闭对话框的函数，触发 "update:modelValue" 事件通知父组件将对话框隐藏，传入false表示隐藏对话框
  const handleClose = () => {
    emits("update:modelValue", false);
  };
  
  // 确认按钮点击时执行的函数，用于验证表单数据并提交保存地址信息
  const handleConfirm = () => {
    ruleFormRef.value.validate(async (valid) => {
        if (valid) {
            try {
                // 将 isDefault 从布尔类型转换为 Integer 类型
                const formData = { ...ruleForm.value };
                formData.isDefault = formData.isDefault ? 1 : 0;
  
                const result = await axios.post("admin/address/save", formData);
                const data = result.data;
                if (data.code == 0) {
                    ElMessage.success("执行成功");
                    ruleFormRef.value.resetFields();
                    emits("initAddressList");
                    handleClose();
                } else {
                    ElMessage.error(data.msg);
                }
            } catch (error) {
                console.error('保存地址信息失败', error);
                ElMessage.error('保存地址信息失败，请检查网络或联系管理员');
            }
        } else {
            console.log("fail");
            return false;
        }
    });
  };
  
  // 监听selectedAddress的变化，当有数据传入时，初始化表单数据
  watch(() => props.selectedAddress, (newValue) => {
      if (newValue) {
          ruleForm.value.id = newValue.id;
          ruleForm.value.userName = newValue.userName;
          ruleForm.value.telNumber = newValue.telNumber;
          ruleForm.value.address = newValue.address;
          ruleForm.value.detailInfo = newValue.detailInfo;
          // 这里将后端返回的 Integer 类型转换为布尔类型
        //   ruleForm.value.isDefault = newValue.isDefault === 1;
          ruleForm.value.isDefault = Number(newValue.isDefault) === 1;
      }
  });
  </script>
  
  <style scoped>
  </style>    